﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WareHouse.App
{
    using System.Drawing.Printing;

    using DevExpress.XtraGrid;
    using DevExpress.XtraPrinting;

    using WareHouse.Contract.Models;
    using WareHouse.Contract.Services;
    using WareHouse.Service.Services;

    public partial class FrmOrder : Form
    {
        private IWareHouseService wareHouseService;

        private List<OrderDetailModel> listOrderDetailModels;
        public FrmOrder()
        {
            listOrderDetailModels = new List<OrderDetailModel>();
            wareHouseService = new WareHouseService();

            InitializeComponent();
            dtgDetailItems.AutoGenerateColumns = false;
        }


        private void CanculateTotal()
        {
            decimal total = 0;
            if (listOrderDetailModels.Count > 0)
            {
                foreach (var item in listOrderDetailModels)
                {
                    total = total + item.Total;
                }
                lblTotal.Text = string.Format("{0:N0}", total);
            }
        }
        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(
              "Bạn có chắc là muốn làm lại", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
              == DialogResult.Yes)
            {
                this.btnCreateImport.Text = "Đơn đặt hàng mới";
                this.RefreshLabel();
                ddlItem.Enabled = false;
                txtQantity.Enabled = false;
                txtPrice.Enabled = false;
                ddlWareHouseImport.Enabled = true;

            }
        }

        private void ddlWareHouseImport_SelectedIndexChanged(object sender, EventArgs e)
        {
          
           
        }


        private void LoadAllCompany()
        {
            ddlWareHouseImport.DataSource = wareHouseService.ListCompany();
            ddlWareHouseImport.DisplayMember = "CompanyName";
            ddlWareHouseImport.ValueMember = "CompanyId";
        }



        private void LoadAllItem()
        {
            ddlItem.Properties.DataSource = wareHouseService.ListItem();
            ddlItem.Properties.DisplayMember = "ItemName";
            ddlItem.Properties.ValueMember = "ItemId";



        }



        private void AddItemToGridDetail()
        {




            if (this.ddlItem.Text == "")
            {
                MessageBox.Show("Bạn phải chọn mặt hàng để bán");
                this.ddlItem.ShowPopup();
                return;
            }
            if (this.txtQantity.Text == "" || int.Parse(this.txtQantity.Text) <= 0)
            {
                MessageBox.Show("Bạn phải nhập số lượng cần bán");
                this.txtQantity.Focus();
                this.txtQantity.SelectAll();
                return;
            }

            var item =
                (ItemModel)
                this.ddlItem.Properties.View.GetRow(
                    this.ddlItem.Properties.GetIndexByKeyValue(this.ddlItem.EditValue));


            if (txtPrice.Text.Trim() == "" || float.Parse(txtPrice.Text) <= 0)
            {
                MessageBox.Show(
                    "Nhập giá cho sản phẩm này");
                txtPrice.Focus();
                txtPrice.SelectAll();
                return;
            }

            var importDetail = new OrderDetailModel();
            importDetail.OrderId = this.lblImportId.Text;
            importDetail.ItemId = item.ItemId;
            importDetail.Quantity = int.Parse(this.txtQantity.Text);
            importDetail.ItemName = item.ItemName;
            importDetail.Price = decimal.Parse(this.txtPrice.Text.Trim() != "" ? this.txtPrice.Text : "0");
            importDetail.Total = importDetail.Quantity * importDetail.Price;


            // add to list

            // check exist in datagrid if exist only update 

            var isExists = this.listOrderDetailModels.Any(x => x.ItemId == importDetail.ItemId);

            if (isExists)
            {
                MessageBox.Show("Sản phẩm này đã có");

                return;
            }

            this.listOrderDetailModels.Add(importDetail);

            this.RefreshGridItemDetail();
            CanculateTotal();
            ddlItem.ShowPopup();

        }

        private void RefreshGridItemDetail()
        {
            this.dtgDetailItems.DataSource = this.listOrderDetailModels.ToArray();
            this.gridItems.DataSource = this.listOrderDetailModels.ToArray();
            this.ReCanculateSTT();
            ReCanculateSTTForDevExpressGridControl();
        }

        private void ddlItem_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            txtQantity.Focus();
        }




        private void btnCreateImport_Click(object sender, EventArgs e)
        {
            if (btnCreateImport.Text == "Đơn đặt hàng mới")
            {
                if (this.ValidateExport())
                {
                    lblImportId.Text = wareHouseService.GetOrder();
                    lblDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    lblWareHouseName.Text = ddlWareHouseImport.Text;
                    lblEmployerName.Text = General.UserFullName;
                    txtPrice.Enabled = true;
                    ddlItem.Enabled = true;
                    txtQantity.Enabled = true;
                    ddlWareHouseImport.Enabled = false;
                    btnCreateImport.Text = "Lưu";
                    lblTotal.Text = "0";
                }

                return;
            }

            if (btnCreateImport.Text == "Lưu")
            {
                if (this.ValidateExport())
                {
                    if (dtgDetailItems.Rows.Count <= 0)
                    {
                        MessageBox.Show("Chưa có mặt hàng nào để bán");
                        return;
                    }
                    if (this.ValidateExport())
                    {
                        if (MessageBox.Show("Bạn có muốn in đơn hàng này sau khi lưu ?","Thông báo",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
                        {
                            this.SaveOrderAndOrderDetail();
                            this.PrintListItemInGrid(gridItems);
                            this.RefreshLabel();
                            return;
                        }

                        this.SaveOrderAndOrderDetail();

                        this.RefreshLabel();
                    }
                }

            }
        }

        private void SaveOrderAndOrderDetail()
        {
            var OrderModel = new OrderModel();
            OrderModel.OrderId = this.lblImportId.Text;
            OrderModel.DateCreate = DateTime.Now;
            OrderModel.CompanyId = int.Parse(this.ddlWareHouseImport.SelectedValue.ToString());
            OrderModel.UserCreate = General.userName;
            OrderModel.LastUpdate = DateTime.Now;
            OrderModel.UpdateBy = General.userName;
            OrderModel.IsFinish = false;
            if (this.wareHouseService.SaveOrder(OrderModel))
            {
                if (this.wareHouseService.SaveOrderDetail(this.listOrderDetailModels, OrderModel))
                {
                    MessageBox.Show("Lưu thành công");
                    this.listOrderDetailModels = new List<OrderDetailModel>();
                    this.ddlItem.Enabled = false;
                    this.txtQantity.Enabled = false;
                    this.ddlWareHouseImport.Enabled = true;
                    this.txtPrice.Enabled = false;
                    this.dtgDetailItems.DataSource = this.listOrderDetailModels;
                    this.btnCreateImport.Text = "Đơn đặt hàng mới";
                    this.LoadAllCompany();
                   
                    return;
                }
                else
                {
                    MessageBox.Show("Có vấn đề xảy ra khi lưu dữ liệu. Xin vui lòng thử lại");
                    return;
                }
            }
            MessageBox.Show("Có vấn đề xảy ra khi lưu dữ liệu. Xin vui lòng thử lại");
        }

        private bool ValidateExport()
        {
            for (int i = 0; i < dtgDetailItems.Rows.Count; i++)
            {
                var newQuantity = int.Parse(dtgDetailItems.Rows[i].Cells["Quantity"].Value.ToString());
                var newPrice = int.Parse(dtgDetailItems.Rows[i].Cells["Price"].Value.ToString());
                if (newPrice <= 0 || newQuantity <= 0)
                {
                    return false;
                }

            }

            if (ddlWareHouseImport.SelectedIndex < 0)
            {
                MessageBox.Show("Chọn kho xuất hàng");
                return false;
            }
            return true;




            return true;

        }
        private void RefreshLabel()
        {

            lblDate.Text = "";
            lblEmployerName.Text = "";
            lblImportId.Text = "";
            lblWareHouseName.Text = "";

        }

        private void dtgDetailItems_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                var itemId = int.Parse(dtgDetailItems.Rows[e.RowIndex].Cells["ItemId1"].Value.ToString());
                var newQuantity = int.Parse(dtgDetailItems.Rows[e.RowIndex].Cells["Quantity"].Value.ToString());
                var newPrice = int.Parse(dtgDetailItems.Rows[e.RowIndex].Cells["Price"].Value.ToString());
                if (itemId > 0)
                {
                    foreach (var item in listOrderDetailModels)
                    {
                        if (item.ItemId == itemId)
                        {
                            if (newQuantity == 0 || newPrice == 0)
                            {
                                MessageBox.Show("Số lượng và Đơn giá phải lớn hơn 0");
                                this.RefreshGridItemDetail();
                                return;
                            }
                            var newTotal = newPrice * newQuantity;
                            item.Total = newTotal;
                            item.Price = newPrice;
                            item.Quantity = newQuantity;
                            this.RefreshGridItemDetail();
                            CanculateTotal();
                            return;
                        }
                    }
                }
            }
            catch (Exception)
            {


            }

        }


        private void ReCanculateSTT()
        {
            for (int i = 0; i < dtgDetailItems.Rows.Count; i++)
            {
                dtgDetailItems.Rows[i].Cells["STT"].Value = i + 1;
            }

        }

        private void ReCanculateSTTForDevExpressGridControl()
        {
            for (int i = 0; i < gridView2.RowCount; i++)
            {
                gridView2.SetRowCellValue(i, "Stt", i + 1);
            }

        }

        private void dtgDetailItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            e.Control.KeyPress -= new KeyPressEventHandler(ColumnQuantity_KeyPress);
            if (dtgDetailItems.CurrentCell.ColumnIndex == 5) //Desired Column
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null)
                {
                    tb.KeyPress += new KeyPressEventHandler(ColumnQuantity_KeyPress);
                }
            }

            if (dtgDetailItems.CurrentCell.ColumnIndex == 6) //Desired Column
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null)
                {
                    tb.KeyPress += new KeyPressEventHandler(ColumnQuantity_KeyPress);
                }
            }
        }

        private void ColumnQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }



        private void txtQantity_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            if ((Keys)e.KeyChar == Keys.Enter)
            {
                txtPrice.Focus();
                txtPrice.SelectAll();
            }
        }

        private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            if ((Keys)e.KeyChar == Keys.Enter)
            {
                this.AddItemToGridDetail();
            }
        }

        private void FrmOrder_Load(object sender, EventArgs e)
        {
            CheckRole();
            this.RefreshLabel();
            LoadAllCompany();
            this.LoadAllItem();
        }
        private void CheckRole()
        {
            if (!wareHouseService.R(General.groupUserId, "order_new"))
            {
                btnCreateImport.Enabled = false;

            }
            if (!wareHouseService.R(General.groupUserId, "orderhistory_read"))
            {
                btnPrintAgain.Enabled = false;

            }


        }
        private void btnPrintAgain_Click(object sender, EventArgs e)
        {
            if (Application.OpenForms["FrmOrderHistory"] == null)
            {
                FrmOrderHistory area = new FrmOrderHistory();
                area.ShowDialog();
                return;

            }
            Application.OpenForms["FrmOrderHistory"].ShowDialog();
        }



        private void printLink_CreateReportHeaderArea(object sender, DevExpress.XtraPrinting.CreateAreaEventArgs e)
        {

            DevExpress.XtraPrinting.TextBrick brick;

            brick = e.Graph.DrawString("ĐƠN ĐẶT HÀNG" + Environment.NewLine + "( " + lblDate.Text + ")", Color.Black, new RectangleF(0, 0, 725, 80), DevExpress.XtraPrinting.BorderSide.None);

            brick.Font = new Font("Tahoma", 22);

            brick.StringFormat = new DevExpress.XtraPrinting.BrickStringFormat(StringAlignment.Center);

        }
        private void PrintListItemInGrid(GridControl gridControl)
        {
            PrintableComponentLink printLink = new PrintableComponentLink();
            printLink.CreateReportHeaderArea += this.printLink_CreateReportHeaderArea;

            PrintingSystem printingSystem = new PrintingSystem();
            printingSystem.Links.AddRange(new object[] { printLink });
            printLink.PaperKind = PaperKind.A4;
            printLink.Component = gridControl;

            printLink.Images.Add(Properties.Resources.Logo);

            printLink.Margins.Top = 200;
            printLink.Margins.Left = 25;
            printLink.Margins.Right = 25;


            var agencyName = "";
            var agencyAddress = "";
            var agencyPhone = "";
            var companyName = "";
            var companyAddress = "";
            var companyPhone = "";

            var company = ddlWareHouseImport.SelectedItem as CompanyModel;
             
                if (company != null)
                {
                    companyAddress = company.CompanyAddress;
                    companyName = company.CompanyName;
                    companyPhone = company.Phone;
                }
                

            
            var currentAgency = wareHouseService.GetCurrentAgency();
            if (currentAgency == null)
            {
                MessageBox.Show("Hiện tại chưa có đại lý nào được chọn");
                return;
            }

            agencyAddress = currentAgency.AgencyAddress;
            agencyName = currentAgency.AgencyName;
            agencyPhone = currentAgency.Phone;
            #region Define content of header
            PageHeaderArea pgHArea = new PageHeaderArea();

            pgHArea.Font = new Font(new FontFamily("Tahoma"), 12, FontStyle.Regular);

            pgHArea.Content.AddRange(
                new string[]
                    {
                        "Đại lý : "+ agencyName+ Environment.NewLine 
                        + "Địa chỉ : "+agencyAddress + Environment.NewLine
                        + "Điện thoại : "+agencyPhone + Environment.NewLine + "  " + Environment.NewLine
                        + "Công ty : "+companyName + Environment.NewLine 
                        + "Địa chỉ : "+companyAddress
                        + Environment.NewLine + "Điện Thoại : "+companyPhone + Environment.NewLine + "" + Environment.NewLine + ""
                        + Environment.NewLine, Environment.NewLine + Environment.NewLine + "", "[Image 0]"
                    });

            #endregion
            #region Define content of footer
            PageFooterArea pgFArea = new PageFooterArea();

            pgFArea.Font = new Font(new FontFamily("Tahoma"), 10, FontStyle.Bold);

            decimal totalSummary = 0;
            var summaryValue = this.gridView2.Columns["Total"].SummaryItem.SummaryValue;
            if (summaryValue != null && decimal.TryParse(summaryValue.ToString(), out totalSummary))
            {
                pgFArea.Content.AddRange(
                new string[]
                    {"","",
                        "Thành tiền : "+ String.Format("{0:N0}",totalSummary)+" VND"+Environment.NewLine
                    +"Bằng chữ :"+ General.DetachMoney((double)totalSummary)
                      
                  
                    });

            }

            #endregion

            // Create a PageHeaderFooter object for this link.
            printingSystem.Links[0].PageHeaderFooter = new PageHeaderFooter(pgHArea, pgFArea);


            printLink.ShowPreview();
        }


    }
}
